package org.jeecg.modules.electronicSeal.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.modules.chexk.service.impl.Base64Util;
import org.jeecg.modules.chexk.service.impl.HttpUtil;
import org.jeecg.modules.electronicSeal.vo.DicElectronicCode;
import org.jeecg.modules.electronicSeal.vo.RequestElectronic;
import org.jeecg.modules.electronicSeal.vo.ResponseStr;
import org.jeecg.modules.order.entity.KuybOrderPolicy;
import org.jeecg.modules.order.mapper.KuybOrderPolicyMapper;
import org.jeecg.modules.order.service.IKuybOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;

@Service
public class ElectronicSealService {
    @Value("${electronicSeal.API_URL}")
    String API_URL="";
    @Value("${electronicSeal.API_TOKEN}")
    String API_TOKEN="";
    @Value("${electronicSeal.API_EMAIL}")
    String API_EMAIL="";
    @Value("${electronicSeal.API_SEAlID}")
    String API_SEAlID="";

    @Autowired
    private IKuybOrderService kuybOrderService;
    @Autowired
    private KuybOrderPolicyMapper kuybOrderPolicyMapper;
    // 临时文件夹获取java system变量中的临时路径，在web项目中是容器的temp文件夹,如果直接运行是系统临时文件夹.
    private static final String FILE_PATH_TEMPLATE = System.getProperty("java.io.tmpdir") + "tempdf/%s";


    public ResponseStr requestSubmitInfo(RequestElectronic sealVo){
       sealVo.setActiontype("requestSubmitInfo");
       sealVo.setNonce(DateUtils.now());
       sealVo.setCountry("CN");
        ResponseStr parseObject=new ResponseStr();
        API_URL= StringUtils.isEmpty(API_URL)? "https://mss1api.mesince.com/api/mesign":API_URL;
        API_TOKEN= StringUtils.isEmpty(API_TOKEN)? "509c8a94-e061-4969-95c4-c305d3e77446":API_TOKEN;
        sealVo.setToken(API_TOKEN);
        try {
           String res= HttpUtil.postGeneralUrl(API_URL,"JSON", JSON.toJSONString(sealVo),"UTF-8");
            parseObject= JSONObject.toJavaObject(JSON.parseObject(res),ResponseStr.class);
            System.out.println(parseObject);
            if(StringUtils.isNotEmpty(parseObject.getToken())){
                //之前签名过，可以直接签章
                parseObject.setReturnCode("1");
                parseObject.setMsg("之前签名过，可以直接签章");
                sealVo.setUserToken(parseObject.getToken());//用户签名
//                requestSign(sealVo);
//                kuybOrderService.getElectronicPolicy(sealVo.getPolicyId(), parseObject.getToken());
            }else if(parseObject.getStatus()==1){
                //发送验证码
                parseObject= requestSendSmsCode(sealVo);
                if(parseObject.getStatus()==1){
                    parseObject.setReturnCode("2");
                    parseObject.setMsg("发送验证码，请输入短信验证码");
                }
            }else{
                //返回错误信息
                parseObject.setReturnCode("3");
                parseObject.setMsg(DicElectronicCode.getValue(parseObject.getErrorcode()));

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return parseObject;
    }

    /**
     * 发动验证码
     * @param sealVo
     * @return
     */
    public ResponseStr requestSendSmsCode(RequestElectronic sealVo){
        ResponseStr parseObject=new ResponseStr();
        API_URL= StringUtils.isEmpty(API_URL)? "https://mss1api.mesince.com/api/mesign":API_URL;
        API_TOKEN= StringUtils.isEmpty(API_TOKEN)? "509c8a94-e061-4969-95c4-c305d3e77446":API_TOKEN;
        sealVo.setToken(API_TOKEN);
        sealVo.setActiontype("requestSendSmsCode");
        sealVo.setNonce(DateUtils.now());
        String res= null;
        try {
            res = HttpUtil.postGeneralUrl(API_URL,"JSON", JSON.toJSONString(sealVo),"UTF-8");
            parseObject= JSONObject.toJavaObject(JSON.parseObject(res),ResponseStr.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return parseObject;
    }

    public ResponseStr requestValidateInfo(RequestElectronic sealVo){
        ResponseStr parseObject=new ResponseStr();
        API_URL= StringUtils.isEmpty(API_URL)? "https://mss1api.mesince.com/api/mesign":API_URL;
        API_TOKEN= StringUtils.isEmpty(API_TOKEN)? "509c8a94-e061-4969-95c4-c305d3e77446":API_TOKEN;
        sealVo.setToken(API_TOKEN);
        sealVo.setActiontype("requestValidateInfo");
        sealVo.setNonce(DateUtils.now());
        String res= null;
        try {
            res = HttpUtil.postGeneralUrl(API_URL,"JSON", JSON.toJSONString(sealVo),"UTF-8");
            parseObject= JSONObject.toJavaObject(JSON.parseObject(res),ResponseStr.class);
            if(StringUtils.isNotEmpty(parseObject.getToken())){
                //之前签名过，可以直接签章
                parseObject.setReturnCode("1");
                parseObject.setMsg("获取userToken成功，可以直接签章");
                sealVo.setUserToken(parseObject.getToken());//用户签名
                // 生产电子保单
//                kuybOrderService.getElectronicPolicy(sealVo.getPolicyId(), parseObject.getToken());
            }else if(parseObject.getStatus()==0){
                parseObject.setReturnCode("3");
                parseObject.setMsg(DicElectronicCode.getValue(parseObject.getErrorcode()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return parseObject;
    }

    public ResponseStr requestSign(RequestElectronic sealVo){
        ResponseStr parseObject=new ResponseStr();
        API_URL= StringUtils.isEmpty(API_URL)? "https://mss1api.mesince.com/api/mesign":API_URL;
        API_TOKEN= StringUtils.isEmpty(API_TOKEN)? "509c8a94-e061-4969-95c4-c305d3e77446":API_TOKEN;
        sealVo.setToken(API_TOKEN);
        sealVo.setActiontype("requestSign");
        sealVo.setNonce(DateUtils.now());
        String res= null;
        sealVo.setShowSinatureEnum(1);
        sealVo.setEmail(API_EMAIL);
        sealVo.setSealID(API_SEAlID);


        KuybOrderPolicy orderPolicy=kuybOrderPolicyMapper.selectById(sealVo.getPolicyId());
        String pdf=netSourceToBase64(orderPolicy.getDianzbdxzdz(),"GET");
        sealVo.setPageindex(1);
        sealVo.setLx(0.72);
        sealVo.setLy(0.04);
        sealVo.setUrx(0.84);
        sealVo.setUry(0.08);
        sealVo.setPdfBytes(pdf);
        parseObject= qianming(sealVo);
        sealVo.setLx(0.59);
        sealVo.setLy(0.09);
        sealVo.setUrx(0.71);
        sealVo.setUry(0.18);
        sealVo.setUserToken("");
        sealVo.setPdfBytes(parseObject.getSignedData());
        parseObject= qianming(sealVo);

        pdf=parseObject.getSignedData();
        String fileName=orderPolicy.getBaodh()==null ? System.currentTimeMillis()+".pdf":orderPolicy.getBaodh()+".pdf";
        base64ToFile(pdf,fileName,FILE_PATH_TEMPLATE);
        FileInputStream inp1= null;
        try {
            inp1 = new FileInputStream(FILE_PATH_TEMPLATE+fileName);
            String url1= MinioUtil.upload(inp1,fileName);
            System.out.println(url1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public ResponseStr requestSign1(String policyId,String userToken,String fileUrl){
        ResponseStr parseObject=new ResponseStr();
        API_URL= StringUtils.isEmpty(API_URL)? "https://mss1api.mesince.com/api/mesign":API_URL;
        API_TOKEN= StringUtils.isEmpty(API_TOKEN)? "509c8a94-e061-4969-95c4-c305d3e77446":API_TOKEN;
        RequestElectronic sealVo=new RequestElectronic();
        sealVo.setToken(API_TOKEN);
        sealVo.setActiontype("requestSign");
        sealVo.setNonce(DateUtils.now());
        sealVo.setUserToken(userToken);
        String res= null;
        sealVo.setShowSinatureEnum(1);
        sealVo.setEmail(API_EMAIL);
        sealVo.setSealID(API_SEAlID);


        KuybOrderPolicy orderPolicy=kuybOrderPolicyMapper.selectById(policyId);
//        String pdf=netSourceToBase64(orderPolicy.getDianzbdxzdz(),"GET");
        String pdf=fileToBase64(fileUrl);
        sealVo.setPageindex(1);
        sealVo.setLx(0.72);
        sealVo.setLy(0.04);
        sealVo.setUrx(0.84);
        sealVo.setUry(0.08);
        sealVo.setPdfBytes(pdf);
        parseObject= qianming(sealVo);
        sealVo.setLx(0.59);
        sealVo.setLy(0.09);
        sealVo.setUrx(0.71);
        sealVo.setUry(0.18);
        sealVo.setUserToken("");
        sealVo.setPdfBytes(parseObject.getSignedData());
        parseObject= qianming(sealVo);

        pdf=parseObject.getSignedData();
        String fileName=orderPolicy.getBaodh()==null ? System.currentTimeMillis()+".pdf":orderPolicy.getBaodh()+".pdf";
        base64ToFile(pdf,fileName,FILE_PATH_TEMPLATE);
        FileInputStream inp1= null;
        try {
            inp1 = new FileInputStream(FILE_PATH_TEMPLATE+fileName);
            String url1= MinioUtil.upload(inp1,fileName);
            orderPolicy.setDianzbdxzdz(url1);
            kuybOrderPolicyMapper.updateById(orderPolicy);
            System.out.println(url1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    private ResponseStr qianming(RequestElectronic sealVo){
        String res= null;
        sealVo.setMobile(null);
        sealVo.setLastname(null);
        sealVo.setFirstname(null);
        sealVo.setState(null);
        sealVo.setCity(null);
        sealVo.setCountry(null);
        sealVo.setCode(null);
        sealVo.setPic1(null);
        sealVo.setPic2(null);
        sealVo.setPic3(null);
        ResponseStr parseObject=new ResponseStr();
        try {
            System.out.println(JSON.toJSONString(sealVo));
            res = HttpUtil.postGeneralUrl(API_URL,"JSON", JSON.toJSONString(sealVo),"UTF-8");//发送请求
            parseObject= JSONObject.toJavaObject(JSON.parseObject(res),ResponseStr.class);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //                inputFile.close();
        }
        return parseObject;
    }

    private static void base64ToFile(String base64, String fileName, String savePath) {
        File file = null;
        //创建文件目录
        String filePath = savePath;
        File dir = new File(filePath);
        if (!dir.exists() && !dir.isDirectory()) {
            dir.mkdirs();
        }
        BufferedOutputStream bos = null;
        java.io.FileOutputStream fos = null;
        try {
            byte[] bytes = Base64.getDecoder().decode(base64);
            file = new File(filePath + fileName);
            fos = new java.io.FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public ResponseStr requestUploadPic(RequestElectronic sealVo) {
        ResponseStr parseObject=new ResponseStr();
        API_URL= StringUtils.isEmpty(API_URL)? "https://mss1api.mesince.com/api/mesign":API_URL;
        API_TOKEN= StringUtils.isEmpty(API_TOKEN)? "509c8a94-e061-4969-95c4-c305d3e77446":API_TOKEN;
        sealVo.setToken(API_TOKEN);
        sealVo.setActiontype("requestUploadPic");
        sealVo.setNonce(DateUtils.now());
        String res= null;
        try {
            res = HttpUtil.postGeneralUrl(API_URL,"JSON", JSON.toJSONString(sealVo),"UTF-8");
            parseObject= JSONObject.toJavaObject(JSON.parseObject(res),ResponseStr.class);
            if(StringUtils.isNotEmpty(parseObject.getToken())){
                //之前签名过，可以直接签章
                parseObject.setReturnCode("1");
                parseObject.setMsg("获取userToken成功，可以直接签章");
                sealVo.setUserToken(parseObject.getToken());//用户签名
//                requestSign(sealVo);
//                kuybOrderService.getElectronicPolicy(sealVo.getPolicyId(), parseObject.getToken());
            }else if(parseObject.getStatus()==0){
                parseObject.setReturnCode("3");
                parseObject.setMsg(DicElectronicCode.getValue(parseObject.getErrorcode()));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return parseObject;
    }
    public static  String fileToBase64(String path) {
        String base64 = null;
        InputStream in = null;
        try {
            File file = new File(path);
            in = new FileInputStream(file);
            byte[] bytes=new byte[(int)file.length()];
            in.read(bytes);
            base64 = Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null)
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
        return base64;
    }


    public static String netSourceToBase64(String srcUrl,String requestMethod) {
        ByteArrayOutputStream outPut = new ByteArrayOutputStream();
        byte[] data = new byte[1024 * 8];
        try {
            // 创建URL
            URL url = new URL(srcUrl);
            // 创建链接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setConnectTimeout(10 * 1000);

            if (conn.getResponseCode() != HttpURLConnection.HTTP_OK) {
                //连接失败/链接失效/文件不存在
                return null;
            }
            InputStream inStream = conn.getInputStream();
            int len = -1;
            while (-1 != (len = inStream.read(data))) {
                outPut.write(data, 0, len);
            }
            inStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(outPut.toByteArray());
    }
}
